package files

import (
	"clouds.lgb24kcs.cn/controllers/files/request"
	"clouds.lgb24kcs.cn/errorx"
	"clouds.lgb24kcs.cn/global"
	"clouds.lgb24kcs.cn/models"
	"clouds.lgb24kcs.cn/utils"
	"clouds.lgb24kcs.cn/utils/history"
	"clouds.lgb24kcs.cn/utils/oss"
	"github.com/gin-gonic/gin"
	"io"
	"net/http"
	"os"
)

type DownloadObjecAPI struct {
}

var DownloadAPI DownloadObjecAPI

func (a DownloadObjecAPI) Download(c *gin.Context, req request.DownloadFileReq, userId int64) {
	fileInfo := models.Files{}
	bucketInfo := models.Storage{}
	api := oss.OSS{}

	tx := global.APP.DB.Where("id=? and bucketname=? and root_dir=? and user_id=?", req.ID, req.BucketNamde, req.CatalogueName, userId).First(&fileInfo)
	tx = global.APP.DB.Where("bucketname=? and userid=?", req.BucketNamde, userId).First(&bucketInfo)
	if tx.Error != nil {
		global.APP.Log.Error(tx.Error.Error())
		utils.Fail(c, errorx.ObjectDownload, tx.Error.Error())
	} else {
		svc := api.NewClient(bucketInfo.Accesskey, bucketInfo.Secretkey, bucketInfo.Zone)
		download := api.ObjectDownload(svc, req.BucketNamde, req.CatalogueName+"/"+fileInfo.Filename) // 这里的Object不需要拼接Bucket上
		//download := api.ObjectDownload(svc, req.BucketNamde, req.BucketNamde+"/"+req.CatalogueName+"/"+fileInfo.Filename)
		open, err := os.Open(download)
		if err != nil {
			global.APP.Log.Error(err.Error())
			utils.Fail(c, errorx.ObjectDownload, err.Error())
		} else {
			defer open.Close()
			var chunk []byte
			buf := make([]byte, 4096)
			for {
				n, err := open.Read(buf)
				if err != nil && err != io.EOF {
					global.APP.Log.Error(err.Error())
				}
				// 读取结束
				if n == 0 {
					break
				}
				// 读取到最终的缓冲区中
				chunk = append(chunk, buf[:n]...)
			}
			if err = history.HistoryCreate(userId, c.Request.Method, c.Request.URL.String(), c.Request.Host); err != nil {
				utils.Fail(c, errorx.ObjectSearch, err.Error())
			} else {
				c.Writer.WriteHeader(http.StatusOK)
				c.Header("Content-Disposition", "attachment; filename="+fileInfo.Filename)
				c.Header("Content-Type", "application/text/plain")
				//c.Header("Accept-Length", fmt.Sprintf("%d", len(download)))
				c.Writer.Write(chunk)
			}

		}

	}
}
